$(function () {
    var _main = $(".main");
    var _goodsId = getUrlParam("id"); // 3365
    var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
    var _contentheight = ($(window).height() - CONFIG_MANAGER.headerHight);

    var goodsDetailPage = function () {
        this.init();
    };
    goodsDetailPage.prototype = {
        // 初始化页面
        init: function () {
            this.loadGoodsDetail();
            this.loadloveitemlist();
            this.addhistory();
            this.bindEvent();
        },
        //加载商品信息
        loadGoodsDetail: function (data) {
            var model = this;
            //商品详情
            var detailajax = $.ajax({
                type: "get",
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/" + _goodsId,
                beforeSend: function () {
                    $.showWaiting();
                }
            }).done(function (data) {
                model.paintGoodsAlbums(data.Albums);
                model.paintGoodsDetail(data);
                model.bindGoodsEvent();
                _choosePage.init(data);
            }).fail(function () {
                $.alert("没找到该商品！");
            }).always(function () {
                $.closeWaiting();
            });

            if (_currentloginuser && _currentloginuser.id) {
                $.ajax({
                        headers: {token: _currentloginuser.token},
                        type: "POST",
                        url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/isgoods/" + _currentloginuser.id + "/" + _goodsId
                    }
                ).done(function (res) {
                    if (res.data == 1) {
                        $("#btnfavorite i").css("color", "#f4514e")[0].className = "iconfont icon-lovefill";
                    }
                }).fail(function (res) {
                    var response = JSON.parse(res.responseText);
                    if (response.Message && response.Message.indexOf("票据") > -1) {
                        $.alert("你的帐号已经在其他地方登录", function () {
                            clearLocalStorage();
                            redirect("../account/login.html");
                            return;
                        });
                    }
                });

                var cacheproductcount = getLocalStorage(STORAGE_MANAGER.cacheproductcount);
                if (cacheproductcount && parseInt(cacheproductcount) > 0) {
                    $("#btnshopcart span").show().text(cacheproductcount);
                } else {
                    $("#btnshopcart span").hide().text(0);
                }

            }

        },

        // 绑定事件
        bindEvent: function () {
            //回退
            $("#back").on("tap", function () {
                back();
            });

            // 置顶
            $("#gotop").on("tap", function () {
                _main.animate({scrollTop: '0px'}, 500);
            });

            // 页面滚动
            _main.scroll(this.isDisplayTopIcon);

            // 更多
            $("#btnmore").on("tap", function () {
                if ($("#morediv").css("display") == "none") {
                    $("#bgdiv").show();
                    $("#moredivicon").show();
                    $("#morediv").show();
                } else {
                    hidemore();
                }
            });

            // 更多菜单
            $("#moreli li").on("tap", function () {
                var tip = $(this).attr("tip");

                if (tip == "0") {
                    // 首页
                    redirect("../home/index.html");
                } else if (tip == "1") {
                    // 分享
                    _sharePage.show();
                }
                else if (tip == "2") {
                    // 搜索
                    showSearchPage();
                }
                hidemore();
            });


            // 猜你喜欢
            $("#loveitemlist").on("tap", "li", function () {
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });


            $("#bgdiv").on("tap", function () {
                hidemore();
            });

            // 隐藏更多
            function hidemore() {
                $("#moredivicon").hide();
                $("#morediv").hide();
                $("#bgdiv").hide();

                $("#choosediv").removeClass("moveFromBottom-moved");
                setTimeout(function () {
                    $("#choosediv").hide();
                }, 300);
            };
        },

        // 商品绑定事件
        bindGoodsEvent: function () {
            // 点击轮播图全屏展示
            $("#banner").on("tap", function () {
                if ($("#banner").hasClass("banner")) {
                    $("#gdmain").addClass("topdingwei");
                    $("#banner")[0].className = "banner-dingwei";
                    $("#tups")[0].className = "tups tups1";
                } else {
                    $("#gdmain").removeClass("topdingwei");
                    $("#banner")[0].className = "banner";
                    $("#tups")[0].className = "tups";
                }
            });

            // 懒加载
            $('img.lazy').lazyload({
                placeholder: "../../images/white.gif",
                container: _main,
                event: "scroll",
                threshold: 100,
                failure_limit: 10
            });

            // 领优惠券
            $("#couponlist span").on("tap", function () {
                var tip = $(this).attr("tip");
            });

            // 送至
            $("#btnregion").on("tap", function () {
                $("#detailpage").hide();
                _regionPage.show();
            });

            // 商品介绍Tab
            var currenttab = $("#currenttab");
            var directionstab = $("#directionstab span");
            currenttab.css({
                width: directionstab.width(),
                "margin-left": directionstab.offset().left,
                "margin-top": "-3px"
            });
            directionstab.on("tap", function () {
                var tip = $(this).attr("tip");
                var activeli = $('#directionstab span[class=current]');
                if (activeli.attr("tip") == tip) {
                    return;
                }
                activeli.removeClass("current");
                $(this).addClass("current");
                var value = "translateX(" + $(this).offset().left + "px)";
                $("#currenttab").css({
                    "margin-left": "0px",
                    "transform": value,
                    "-webkit-transform": value,
                    "-o-transform": value,
                    "-ms-transform": value
                });
                $("div[name=tab]:visible").hide();
                $("#tab" + tip).show();
            });

            // 更多评价
            $("#btnmoreappraise").on("tap", function () {
                $("#appraisepage").show(300);
                $("#detailpage").hide();
                _goodsCommentsPage.show();
            });

            // 进入店铺
            $("#btnentershop").on("tap", function () {
                redirect("../shop/shop.html?id=" + $(this).attr("tip"));
            });

            // 收藏
            $("#btnfavorite").on("tap", function () {
                if (!_currentloginuser) {
                    // 用户若无登录，必须登录
                    redirect("../account/login.html");
                    return;
                }
                var current = $(this).find("i");
                if (current.hasClass('icon-love')) {
                    // 收藏
                    current.css("color", "#f4514e")[0].className = "iconfont icon-lovefill";
                    $.ajax({
                        headers: {token: _currentloginuser.token},
                        type: "POST",
                        url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/goods/" + _currentloginuser.id + "/" + _goodsId
                    }).done(function (res) {

                    }).fail(function (res) {
                        var response = JSON.parse(res.responseText);
                        if (response.Message && response.Message.indexOf("票据") > -1) {
                            $.alert("你的帐号已经在其他地方登录", function () {
                                clearLocalStorage();
                                redirect("../account/login.html");
                                return;
                            });
                        }
                    });
                } else {
                    // 取消收藏
                    current.css("color", "#000000")[0].className = "iconfont icon-love";
                    $.ajax({
                        headers: {token: _currentloginuser.token},
                        type: "DELETE",
                        url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/goods/" + _currentloginuser.id + "/" + _goodsId
                    }).done(function (res) {

                    }).fail(function (res) {
                        var response = JSON.parse(res.responseText);
                        if (response.Message && response.Message.indexOf("票据") > -1) {
                            $.alert("你的帐号已经在其他地方登录", function () {
                                clearLocalStorage();
                                redirect("../account/login.html");
                                return;
                            });
                        }
                    });
                }
            });

            // 跳转购物车
            $("#btnshopcart").on("tap", function () {
                if (!_currentloginuser) {
                    // 用户若无登录，必须登录
                    redirect("../account/login.html");
                    return;
                }

                redirect("../shopcart/shoppingcart.html");
            });
            // 加入购物车
            $("#btnbuy span").on("tap", function () {
                if (!_currentloginuser) {
                    // 用户若无登录，必须登录
                    redirect("../account/login.html");
                    return;
                }
                $("#btnbuy span[clicked=true]").attr("clicked", false);
                $(this).attr("clicked", true);

                _choosePage.show();
                var tip = $(this).attr("tip");
                if (tip == "0") {
                    // 加入购物车

                } else if (tip == "1") {
                    // 立即购买

                } else {

                }
            });
        },

        // 商品相册
        paintGoodsAlbums: function (albums) {
            if (!albums || albums.length == 0) {
                return;
            }
            var html = [];
            $.each(albums, function (i, pic) {
                html.push("<li><img class='lazy' data-original='" + getImageUrl(pic.identify, 1080, 1044) + "' /></li>");
            })
            $("#goodspiclist").html(html.join(''));
            $(".slider").touchSlider({
                width: 375,
                height: 363,
                during: 3000,
                autoplay: false,
                showindr: false,
                move: function (currindex, total) {
                    $("#tups").text((currindex + 1) + "/" + total);
                    // 商品图片滑动懒加载
                    $('img.lazy').lazyload({
                        placeholder: "../../images/white.gif",
                        container: $(".slider"),
                        threshold: 100,
                        failure_limit: 10
                    });
                }
            });

            $("#tups").text("1/" + $(".slider li").length);
        },

        // 画商品详情
        paintGoodsDetail: function (goodsInfo) {
            var html = [];
            // 商品基本信息
            html.push("<div class='muokuaibg mbtopbottom'>");
            html.push("<p class='xfxxqbt'>" + goodsInfo.name + goodsInfo.specs + goodsInfo.title + "</p>");
            if (goodsInfo.Is_coin == 1) {
                html.push("<p class='cpxqjg'><span class='jinbi'><b><img src='../../images/jbtub.jpg'></b>" + goodsInfo.coin + "</span>+<span class='money'>￥" + goodsInfo.sku_actprice + "</span></p>");
            } else {
                html.push("<p class='cpxqjg'>￥" + goodsInfo.shop_price + "<span>市场价：" + goodsInfo.market_price + "</span></p>");
            }
            html.push("</div>");

            // 优惠券
            html.push("<div class='cpxqcx bgbai mbtopbottom mtb5'>");
            html.push("<div class='lquan mbbottom'>");
            html.push("<p class='lquanbt'>领券</p>");
            html.push("<div class='lquanny'>");
            html.push("<span class='liangh'>￥20元优惠券</span>");
            html.push("<span>￥50元优惠券</span>");
            html.push("<span>￥100元优惠券</span>");
            html.push("</div>");
            html.push("</div>");
            html.push("<div class='cxfsbg mbbottom'>");
            html.push("<p class='cxfsbt'>促销<span>可享受的促销方式</span></p>");
            html.push("<p class='mansong mbbottom'><span class='mansongan'>满送</span><span>全场购买满¥1000将赠送热销商品，送完为止</span><span class='xqyjt'><i class='iconfont icon-jiantou2'></i></span></p>");
            html.push("<p class='mansong'><span class='mansongan'>满减</span><span>全场购买满¥500立减100，去凑单</span><span class='xqyjt'><i class='iconfont  icon-jiantou2'></i></span></p>");
            html.push("</div>");
            html.push("<p class='cxfsbt mleft10' id='btnregion'>送至<span>上海 > 长宁区 > 内环以外</span></p>");
            html.push("<p class='cxfsbt storestatus' id='storestatus'>有货</p>");
            html.push("</div>");

            // 商品评价
            html.push("<div class='muokuaibg mbtopbottom mtop5'>");
            html.push("<h2 class='xfxianbt mbbottom'>商品评价</h2>");
            html.push("<div id='briefcomments'></div>")
            html.push("<p class='ckgd' id='btnmoreappraise'>查看更多评价<span></span></p>");
            html.push("</div>");

            // 店铺详情
            html.push("<div class='mbtopbottom bgbai mtb5'><div class='dpnybt'>");
            html.push("<p class='dplbytx'><img class='lazy' data-original='" + getImageUrl(goodsInfo.shop_logo, 90, 90) + "'/></p>");
            html.push("<p class='dplbywz'><span>" + goodsInfo.shop_name + "</span><br/>" + goodsInfo.sku_nums + "件产品 ▪ " + goodsInfo.sku_favorites + "人关注</p>");
            html.push("<p class='dpllyjrdp' id='btnentershop' tip='" + goodsInfo.shop_id + "'>进入店铺</p></div></div>");

            // 店铺介绍，包装规格，售后服务
            html.push("<div class='spxqbg'>");
            html.push("<p class='spxqbt bgbai mbbottom ' id='directionstab'><span class='current' tip='0'>商品介绍</span><span tip='1'>规格参数</span><span tip='2'>包装售后</span></p>");

            html.push(" <div id='currenttab' class='xqbthg'></div>");

            html.push("<div id='tab0' name='tab'>");
            html.push("<div class='spjs' style='width: 100%;margin: 0px'>");
            if (goodsInfo.content) {
                var contenthtml = $("<div></div>");
                var imglist = contenthtml.html(goodsInfo.content).find("img");
                if (imglist && imglist.length > 0) {
                    $.each(imglist, function (i, img) {
                        var imgkey = $(img).attr("src");
                        $(img).attr({"src": '', "data-original": getImageUrl(imgkey, 1080, 510)})[0].className = "lazy";
                    });
                }

                html.push(contenthtml.html());
            }
            html.push("</div></div>");

            html.push("<div id='tab1' name='tab' style='display:none'>");
            html.push("<div class='spjs' style='width: 90%;'>");
            if (goodsInfo.Paras && goodsInfo.Paras.length > 0) {
                html.push("<table class='ggcs' border='1px' cellspacing='0px'  bordercolor='#ccc'>");
                html.push("<tr><td class='ggcsleft'></td><td class='ggcsright spscbt'>主体</td></tr>");
                $.each(goodsInfo.Paras, function (i, para) {
                    html.push("<tr><td class='ggcsleft'>" + para.name + "</td><td class='ggcsright'>" + para.value + "</td></tr>");
                })
                html.push("</table>")
            }
            html.push("</div></div>");
            html.push("<div id='tab2' name='tab' style='display:none'>");
            html.push("<div class='spjs' style='width: 90%;'>");
            html.push("<p class='bzqd mbbottom'><span>包装清单：</span><br/>" + goodsInfo.package + "</p>");
            html.push("<p class='fwznbt '>服务承诺</p>");
            html.push("<p class='chengnou'><span>如此生活向您承诺：</span>所售商品均为正品行货，‘如此生活’自营商品开具机打发票或电子发票。凭质保证书及‘如此生活’发票，可享受全国联保服务（奢侈品、钟表除外；奢侈品、钟表由‘如此生活’联系保修，享受法定三包售后服务），与您亲临商场选购的商品享受相同的质量保证。‘如此生活’还为您提供具有竞争力的商品价格和运费政策，请您放心购买！</p>");
            html.push("<p class='chengnou'><span>注：</span>因厂家会在没有任何提前通知的情况下更改产品包装、产地或者一些附件，本司不能确保客户收到的货物与商城图片、产地、附件说明完全一致。只能确保为原厂正货！并且保证与当时市场上同样主流新品一致。若本商城没有及时更新，请大家谅解 </p>");
            html.push("</div></div>");

            html.push("</div>");

            $("#goodsDetailInfo").html(html.join(""));
        },

        // 评论3条数据
        paintComments: function (data) {
            var html = [];
            for (var i = 0; i < data.list.length; i++) {
                var item = data.list[i];
                html.push("<div class='mbbottom xfpinglun'>");
                html.push("<p class='pltxmzsj'><b><img src='" + CONFIG_MANAGER.imgeUrl + item.avatar + "'/></b>" + item.member_name + "<span>" + dateDiff(new Date(item.create_time_text).getTime()) + "</span></p>");
                html.push("<p class='plnr'>" + item.content + "</p>");
                html.push("</div>");
                if (i == 2) {
                    break;
                }
            }
            var count = data.all_count && data.all_count > 0 ? "(" + data.all_count + ")" : "";
            $("#btnmoreappraise span").text(count);
            $("#briefcomments").html(html.join(""));
        },

        // 检查库存
        checkInventory: function (regionid, regiontext) {
            $("#detailpage").show();
            if (regionid) {
                $("#btnregion span").text(regiontext).attr("tag", regionid);

                $.ajax({
                    type: "POST",
                    url: CONFIG_MANAGER.RequstUrl + "v1/goods/stocks/" + regionid + "?skuids=" + _goodsId
                }).done(function (res) {
                    var status = (res.data && res.data.length > 0 && res.data[0].iventory > 0) ? "有货" : "无货";
                    $("#storestatus").text(status);
                });
            }
        },

        // 猜你喜欢
        loadloveitemlist: function () {
            if (!_currentloginuser) {
                return;
            }
            $.ajax({
                type: 'GET',
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/rank/like/" + _currentloginuser.id + "/" + 6
            }).done(function (res) {
                if (!res || res.length == 0) {
                    return;
                }
                var html = [];
                html.push("<div class='cnxhdbg'><h2 class='cnxhdbiaoti'><span class='bghui'>猜你喜欢的</span></h2><ul class='cnxhd' >")
                $.each(res, function (i, goodsitem) {
                    html.push("<li class='syxhd' name='lovegoodsitem' tip='" + goodsitem.sku_id + "'><dl><dt><img class='lazy' data-original='" + getImageUrl(goodsitem.logo, 496, 466) + "'  src='../../images/place/496x466.png'></dt><dd>" + goodsitem.name + goodsitem.title + "</dd><dd class='xhmony'>￥" + goodsitem.shop_price + "</dd></dl></li>");
                });
                html.push("</ul></div>");
                $("#loveitemlist").html(html.join(""));

                // 懒加载
                $('img.lazy').lazyload({
                    placeholder: "../../images/white.gif",
                    container: "#loveitemlist",
                    event: "scroll",
                    threshold: 100,
                    failure_limit: 10
                });
            });
        },

        // 添加购物车或立即购买
        addbuygoods: function (skuid, qty) {
            if ($("#btnbuy span[clicked=true]").attr("tip") == "0") {
                var postdata =
                {
                    member_id: _currentloginuser.id,
                    session_id: getSessionID(),
                    sku_id: skuid,
                    qty: qty,
                    activity_no: "",
                    suit_no: ""
                };
                $.ajax({
                    type: "POST",
                    url: CONFIG_MANAGER.RequstUrl + "v1/cart/addcart",
                    data: postdata
                }).done(function (res) {
                    $("#btnshopcart span").text(parseInt($("#btnshopcart span").text()) + 1).show();
                });
            }
        },

        // 浏览记录
        addhistory: function () {
            if (!_currentloginuser) {
                return;
            }
            var postdata =
            {
                member_id: _currentloginuser.id,
                session_id: getSessionID(),
                sku_id: _goodsId
            };
            $.ajax({
                headers: {'Content-Type': 'application/json'},
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/history",
                data: JSON.stringify(postdata),
            }).always(function (res) {

            });
        },

        // 判断显示置顶图标
        isDisplayTopIcon: function (y) {
            var top = _main.scrollTop();
            if (top > _contentheight / 2) {
                $("#gotop").show();
            } else {
                $("#gotop").hide();
            }
        },
    };

    // 商品选择页面
    var _choosePage = new choosePage();

    // 详情页面
    var _goodsDetailPage = new goodsDetailPage();

    // 分享页面
    var _sharePage = new sharePage();

    // 评价页面
    var _goodsCommentsPage = new goodsCommentsPage();
    _goodsCommentsPage.back = function () {
        _goodsCommentsPage.hide();
        $("#detailpage").show();
    }
    _goodsCommentsPage.initEnd = function (data) {
        _goodsDetailPage.paintComments(data);
    }
    // 区域页面
    var _regionPage = new regionPage();
    _regionPage.getResult = function (regionid, regiontext) {
        _goodsDetailPage.checkInventory(regionid, regiontext);
    }

    // 商品选择确认
    _choosePage.confirm = function (skuid, qty) {
        _goodsDetailPage.addbuygoods(skuid, qty);
    }
});

// 关闭搜索页
function showSearchPage() {
    $("#searchiframe").show();
    searchiframe.window.loadSearchHistory();
}

// 关闭搜索页
function closeSearchPage() {
    $("#searchiframe").hide();
}
